package com.edu.whty.common.tools;

import org.apache.commons.lang.StringUtils;

import java.math.BigDecimal;

public class CovertUtil {

	public static int covertFile(String size) {

		String fileLength = "0";
		try {
			if (StringUtils.isNotEmpty(size)) {
				String fsize = size.replace(" ", "").toLowerCase();
				if (fsize.indexOf("kb") == -1 && fsize.indexOf("mb") == -1
						&& fsize.indexOf("gb") == -1
						&& fsize.indexOf("b") != -1) {
					fileLength = fsize.substring(0, fsize.indexOf("b"));
					BigDecimal b1 = new BigDecimal(
							Double.parseDouble(fileLength));
					BigDecimal b = new BigDecimal(1);
					String lenght = String.valueOf(b1.multiply(b));
					;
					if (lenght.indexOf(".") != -1) {
						fileLength = lenght.substring(0, lenght.indexOf("."));
					} else {
						fileLength = lenght;
					}
				}
				;
				if (fsize.indexOf("kb") != -1) {
					fileLength = fsize.substring(0, fsize.indexOf("kb"));
					BigDecimal b1 = new BigDecimal(
							Double.parseDouble(fileLength));
					BigDecimal b = new BigDecimal(1024);
					String lenght = String.valueOf(b1.multiply(b));
					;
					if (lenght.indexOf(".") != -1) {
						fileLength = lenght.substring(0, lenght.indexOf("."));
					} else {
						fileLength = lenght;
					}
				}
				;
				if (fsize.indexOf("mb") != -1) {
					fileLength = fsize.substring(0, fsize.indexOf("mb"));
					BigDecimal b1 = new BigDecimal(
							Double.parseDouble(fileLength));
					BigDecimal b = new BigDecimal(1024 * 1024);
					String lenght = String.valueOf(b1.multiply(b));
					;
					if (lenght.indexOf(".") != -1) {
						fileLength = lenght.substring(0, lenght.indexOf("."));
					} else {
						fileLength = lenght;
					}
				}
				;
				if (fsize.indexOf("gb") != -1) {
					fileLength = fsize.substring(0, fsize.indexOf("gb"));
					BigDecimal b1 = new BigDecimal(
							Double.parseDouble(fileLength));
					BigDecimal b = new BigDecimal(1024 * 1024 * 1024);
					String lenght = String.valueOf(b1.multiply(b));
					;
					if (lenght.indexOf(".") != -1) {
						fileLength = lenght.substring(0, lenght.indexOf("."));
					} else {
						fileLength = lenght;
					}
				}
				;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return Integer.parseInt(fileLength);
	}

	public static String covertFilePrex(String fileSize) {
        if(StringUtils.isEmpty(fileSize)){
        	return "0";
        }
        if(fileSize.contains("B")){
        	return fileSize;
        }
		long size = Long.parseLong(fileSize);


		long kb = 1024;
		long mb = kb * 1024;
		long gb = mb * 1024;

		if (size >= gb) {
			return String.format("%.2fGB", (float) size / gb);
		} else if (size >= mb) {
			float f = (float) size / mb;
			return String.format("%.2fMB", f);
		} else if (size >= kb) {
			float f = (float) size / kb;
			return String.format("%.2fKB", f);
		} else
			return String.format("%dB", size);
	

	}
	
	public static void main(String[] args) {
		System.out.println(covertFilePrex("4058400"));
	}
}
